﻿/*----------------------------------------------------------------
// Copyright (C) ET
// 版权所有。 
//
// 文件名：PersonnelDAL

// 文件功能描述：人员操作

// 创建标识：胡进财 20140829
 
// 修改标识：

// 修改描述：

//----------------------------------------------------------------*/
using System.Collections;
using System.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace ET.Monitor.DAL
{
    public class PersonnelDAL
    {
        object objJudge = null;
        string strSql = "", strErrMsg = "";
        DataTable dtTable = new DataTable();
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();
        DataTable dtList = new DataTable();

        InvokeWebService iw = new InvokeWebService();
        string rtdbRelationAddress = "";
        string rtdbRealTimeAddress = "";
        string rtdbNameSpace = "";
        string rtdbJudge = "";

        public PersonnelDAL()
        {
            rtdbRelationAddress = ConfigurationManager.ConnectionStrings["RelationURL"].ConnectionString;
            rtdbRealTimeAddress = ConfigurationManager.ConnectionStrings["RealTimeURL"].ConnectionString;
            rtdbNameSpace = ConfigurationManager.ConnectionStrings["NameSpace"].ConnectionString;
            rtdbJudge = ConfigurationManager.ConnectionStrings["Judge"].ConnectionString;
        }

        #region 获取角色编码
        /// <summary>
        /// 获取角色编码
        /// </summary>
        /// <param name="uid">用户编码</param>
        /// <returns></returns>
        public string GetGroup(string uid)
        {
            strSql = "select T_GRPID from T_SYS_MEMBERGRP where T_USERID='" + uid + "'";
            objJudge = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            string uName = "";
            if (objJudge != null)
                uName = objJudge.ToString();
            return uName;
        }
        #endregion









        #region 判断是否存在某个用户
        /// <summary>
        /// 判断是否存在某个用户
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public object CheckUser(string userName, string pwd)
        {
            strSql = "select count(*) from T_SYS_MEMBERINFO where T_USERID='" + userName + "' and T_PASSWORD='" + pwd + "'";
            objJudge = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });

            return objJudge;
        }



        #endregion

        #region 获取登陆姓名
        /// <summary>
        /// 获取登陆姓名
        /// </summary>
        /// <param name="uid">用户编码</param>
        /// <returns></returns>
        public string GetUserName(string uid)
        {
            strSql = "select T_USERNAME from T_SYS_MEMBERINFO where T_USERID='" + uid + "'";
            objJudge = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            string uName = "";
            if (objJudge != null)
                uName = objJudge.ToString();
            return uName;
        }
        #endregion

        #region  获取上一级组织机构信息
        /// <summary>
        /// 获取组织机构编码
        /// </summary>
        /// <param name="uid">用户编码</param>
        /// <returns></returns>
        public object GetOrgid(string uid)
        {
            strSql = "select T_ORGID from T_SYS_MEMBERORG where T_USERID='" + uid + "'";
            object obj = new object();
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            return obj;
        }

        public DataTable GetOrgids(string uid)
        {
            strSql = "select T_ORGID from T_SYS_MEMBERORG where T_USERID='" + uid + "'";
            object obj = new object();
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dt;
        }

        #endregion


        #region 添加用户
        public bool AddUser(string userGrp, string userId, string userName, string userPwd, string userOrg, string userLangu, string userPhone, string userEmail, byte[] userPhoto, string userPhotoName)
        {
            bool judge = false;
            string errMsg = "";
            string sql1 = "select * from T_SYS_MEMBERINFO where T_USERID='" + userId + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { sql1, strErrMsg });

            if (dt == null || dt.Rows.Count == 0)
            {
                if (userPhoto == null)
                {
                    string sql2 = "insert into T_SYS_MEMBERINFO (T_USERID,T_USERNAME,T_PASSWORD,T_LANGUAGE,T_EMAIL,T_PHONE) values ('" + userId + "','" + userName + "','" + userPwd + "','" + userLangu + "','" + userEmail + "','" + userPhone + "')";
                    iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { sql2, strErrMsg });
                    if (errMsg == "")
                    {
                        judge = true;
                    }
                    else
                    {
                        judge = false;
                    }
                }
                else
                {
                    dtList = new DataTable();
                    dtList.Columns.Add("key");
                    dtList.Columns.Add("value");

                    DataRow dr = dtList.NewRow();

                    dr = dt.NewRow(); dr["key"] = "T_USERID"; dr["value"] = userId; dtList.Rows.Add(dr);
                    dr = dt.NewRow(); dr["key"] = "T_USERNAME"; dr["value"] = userName; dtList.Rows.Add(dr);
                    dr = dt.NewRow(); dr["key"] = "T_PASSWORD"; dr["value"] = userPwd; dtList.Rows.Add(dr);
                    dr = dt.NewRow(); dr["key"] = "T_LANGUAGE"; dr["value"] = userLangu; dtList.Rows.Add(dr);
                    dr = dt.NewRow(); dr["key"] = "T_EMAIL"; dr["value"] = userEmail; dtList.Rows.Add(dr);
                    dr = dt.NewRow(); dr["key"] = "T_PHONE"; dr["value"] = userPhone; dtList.Rows.Add(dr);
                    dr = dt.NewRow(); dr["key"] = "T_ATTACHMENTNAME"; dr["value"] = userPhotoName; dtList.Rows.Add(dr);
                    //dr = dt.NewRow(); dr["key"] = "B_ATTACHMENT"; dr["value"] = userPhoto; dtList.Rows.Add(dr);
                    ds.Tables.Add(dtList);

                    //List<Hashtable> list = new List<Hashtable>();
                    //Hashtable ht = new Hashtable(); ht.Add("key", "T_USERID"); ht.Add("value", userId); list.Add(ht);
                    //ht = new Hashtable(); ht.Add("key", "T_USERNAME"); ht.Add("value", userName); list.Add(ht);
                    //ht = new Hashtable(); ht.Add("key", "T_PASSWORD"); ht.Add("value", userPwd); list.Add(ht);
                    //ht = new Hashtable(); ht.Add("key", "T_LANGUAGE"); ht.Add("value", userLangu); list.Add(ht);
                    //ht = new Hashtable(); ht.Add("key", "T_EMAIL"); ht.Add("value", userEmail); list.Add(ht);
                    //ht = new Hashtable(); ht.Add("key", "T_PHONE"); ht.Add("value", userPhone); list.Add(ht);
                    //ht = new Hashtable(); ht.Add("key", "T_ATTACHMENTNAME"); ht.Add("value", userPhotoName); list.Add(ht);

                    //judge = db.UpDocument(list, "T_SYS_MEMBERINFO", "B_ATTACHMENT", userPhoto);

                    judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "UpDocument", new object[] { ds, "T_SYS_MEMBERINFO", "B_ATTACHMENT", userPhoto });

                }
                string sql3 = "";
                string[] Orgs = userOrg.Split(',');
                for (int i = 0; i < Orgs.Length; i++)
                {
                    sql3 = sql3 + "insert into T_SYS_MEMBERORG (T_USERID,T_ORGID) values ('" + userId + "','" + Orgs[i] + "');";
                }
                dt = null;
                sql1 = "select * from T_SYS_MEMBERGRP where T_USERID='" + userId + "'";
                dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { sql1, strErrMsg });

                if (dt == null || dt.Rows.Count == 0)
                {
                    sql3 = sql3 + "insert into T_SYS_MEMBERGRP (T_USERID,T_GRPID) values ('" + userId + "','" + userGrp + "');";
                    judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { sql3, strErrMsg });
                }
            }
            else
            {
                judge = false;
            }

            return judge;
        }
        #endregion

        #region 编辑用户
        public bool EditUser(string userGrp, string userId, string userName, string userPwd, string userOrg, string userLangu, string userPhone, string userEmail, byte[] userPhoto, string userPhotoName)
        {
            bool judge = false;
            string errMsg = "";
            if (userPhoto == null)
            {
                strSql = "update T_SYS_MEMBERINFO set T_USERNAME='" + userName + "', T_PASSWORD='" + userPwd + "', T_LANGUAGE='" + userLangu + "', T_EMAIL='" + userEmail + "', T_PHONE='" + userPhone + "' where T_USERID='" + userId + "'";
                iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
                if (errMsg == "")
                {
                    judge = true;
                }
                else
                {
                    judge = false;
                }
            }
            else
            {
                strSql = "delete from T_SYS_MEMBERINFO where T_USERID='" + userId + "'";
                iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });


                DataSet dsWhere = new DataSet();
                DataTable dtWhere = new DataTable();
                dtWhere.Columns.Add("key");
                dtWhere.Columns.Add("value");

                DataRow drWhere = dtWhere.NewRow(); drWhere["key"] = "T_USERID"; drWhere["value"] = userId; dtWhere.Rows.Add(drWhere);
                drWhere = dtWhere.NewRow(); drWhere["key"] = "T_USERNAME"; drWhere["value"] = userName; dtWhere.Rows.Add(drWhere);
                drWhere = dtWhere.NewRow(); drWhere["key"] = "T_PASSWORD"; drWhere["value"] = userPwd; dtWhere.Rows.Add(drWhere);
                drWhere = dtWhere.NewRow(); drWhere["key"] = "T_LANGUAGE"; drWhere["value"] = userLangu; dtWhere.Rows.Add(drWhere);
                drWhere = dtWhere.NewRow(); drWhere["key"] = "T_EMAIL"; drWhere["value"] = userEmail; dtWhere.Rows.Add(drWhere);
                drWhere = dtWhere.NewRow(); drWhere["key"] = "T_PHONE"; drWhere["value"] = userPhone; dtWhere.Rows.Add(drWhere);
                drWhere = dtWhere.NewRow(); drWhere["key"] = "T_ATTACHMENTNAME"; drWhere["value"] = userPhotoName; dtWhere.Rows.Add(drWhere);
                //drWhere = dtWhere.NewRow(); drWhere["key"] = "B_ATTACHMENT"; drWhere["value"] = userPhoto; dtWhere.Rows.Add(drWhere);

                dsWhere.Tables.Add(dtWhere);



                //List<Hashtable> list = new List<Hashtable>();
                //Hashtable ht = new Hashtable(); ht.Add("key", "T_USERID"); ht.Add("value", userId); list.Add(ht);
                //ht = new Hashtable(); ht.Add("key", "T_USERNAME"); ht.Add("value", userName); list.Add(ht);
                //ht = new Hashtable(); ht.Add("key", "T_PASSWORD"); ht.Add("value", userPwd); list.Add(ht);
                //ht = new Hashtable(); ht.Add("key", "T_LANGUAGE"); ht.Add("value", userLangu); list.Add(ht);
                //ht = new Hashtable(); ht.Add("key", "T_EMAIL"); ht.Add("value", userEmail); list.Add(ht);
                //ht = new Hashtable(); ht.Add("key", "T_PHONE"); ht.Add("value", userPhone); list.Add(ht);
                //ht = new Hashtable(); ht.Add("key", "T_ATTACHMENTNAME"); ht.Add("value", userPhotoName); list.Add(ht);

                judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "UpDocument", new object[] { dsWhere, "T_SYS_MEMBERINFO", "B_ATTACHMENT", userPhoto });


                //judge = db.UpDocument(list, "T_SYS_MEMBERINFO", "B_ATTACHMENT", userPhoto);


            }
            strSql = "delete from T_SYS_MEMBERORG where T_USERID='" + userId + "'";
            iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
            strSql = "delete from T_SYS_MEMBERGRP where T_USERID='" + userId + "'";
            iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
            string sql3 = "";
            string[] Orgs = userOrg.Split(',');
            for (int i = 0; i < Orgs.Length; i++)
            {
                if(Orgs[i] !="")
                {

                    sql3 = sql3 + "insert into T_SYS_MEMBERORG (T_USERID,T_ORGID) values ('" + userId + "','" + Orgs[i] + "');";
                }
            }
            sql3 = sql3 + "insert into T_SYS_MEMBERGRP (T_USERID,T_GRPID) values ('" + userId + "','" + userGrp + "');";
            judge = (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { sql3, strErrMsg });

            return judge;
        }
        #endregion

        #region 读取用户头像
        public DataTable DownUserPhoto(string userId)
        {
            bool ret = true;
            string errMsg = "";
            string sqlstr = "select * from T_SYS_MEMBERINFO where T_USERID='" + userId + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { sqlstr, strErrMsg });
            return dt;
        }
        #endregion

        #region 删除用户
        public bool DelUser(string userId)
        {
            string errMsg = "";
            strSql = "delete from T_SYS_MEMBERORG where T_USERID='" + userId + "';delete from T_SYS_MEMBERINFO where T_USERID='" + userId + "';delete from T_SYS_MEMBERGRP where T_USERID='" + userId + "';";
            iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });

            if (errMsg == "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除组织机构时，同时删除该组织机构下的所有与用户关联的信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public bool DeleteUserRelateOrg(string orgId)
        {
            strSql = "delete from T_SYS_MEMBERORG where  T_ORGID='" + orgId + "'";
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 用户关联组织机构
        public bool AddUserRelateOrg(string userId, string orgId)
        {
            strSql = @"INSERT INTO T_SYS_MEMBERORG (T_USERID,T_ORGID) VALUES ('" + userId + "','" + orgId + "');";
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }
        #endregion

        static string ids = "";
        public void GetId(string id)
        {
            string oid = "";
            strSql = "select T_ORGID from T_BASE_ORG where T_PARENTID in(" + id + ")";
            dtTable = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            if (dtTable != null && dtTable.Rows.Count > 0)
            {
                for (int i = 0; i < dtTable.Rows.Count; i++)
                {
                    ids += "'" + dtTable.Rows[i][0] + "',";
                    oid += "'" + dtTable.Rows[i][0] + "',";
                }
            }
            if (oid.Length > 0)
            {
                oid = oid.Substring(0, oid.Length - 1);
                GetId(oid);
            }
        }

        public DataTable GetStations(string userId)
        {
            DataTable dt = new DataTable();
            strSql = "select T_ORGID from T_SYS_MEMBERORG where T_USERID='" + userId + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    stationId += "'" + dt.Rows[i][0] + "',";
                }
            }

            if (stationId.Length > 0)
                stationId = stationId.Substring(0, stationId.Length - 1);


            strSql = @"select p.T_ORGID,T_PLANTDESC,p.D_LAT,p.D_LONG,t.T_POWERTAG,t.T_ELECTAG,t.T_IRRADIANCETAG from T_INFO_PLANT p left join T_BASE_POINTS_ORG t on p.T_ORGID = t.T_ORGID where p.T_ORGID in(" + stationId + ")";
            stationId = "";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });


            DataTable tblDatas = new DataTable("Station");
            DataColumn dc = null;

            //赋值给dc，是便于对每一个datacolumn的操作
            dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;//

            dc = tblDatas.Columns.Add("stationId", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("stationName", Type.GetType("System.String"));
            //dc = tblDatas.Columns.Add("data", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("power", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("rl", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("dl", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("lat", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("long", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("ratio", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("state", Type.GetType("System.String"));
            DataRow dr;
            if (dt != null && dt.Rows.Count > 0)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strSql = "select T_DISTRICTID From T_BASE_DISTRICT where T_ORGID='" + dt.Rows[i]["T_ORGID"] + "'";
                    DataTable dtD = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

                    double rl = 0;
                    for (int k = 0; k < dtD.Rows.Count; k++)
                    {
                        strSql = " select top 1 D_RL From T_INFO_RL where T_ORGID='" + dtD.Rows[k][0] + "' order by T_TIME desc";
                        object obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
                        if (obj != null)
                            rl += Convert.ToDouble(obj);
                    }

                    dr = tblDatas.NewRow();
                    dr["stationId"] = dt.Rows[i]["T_ORGID"].ToString();
                    dr["stationName"] = dt.Rows[i]["T_PLANTDESC"].ToString();

                    double power = 0;
                    double fzd = 0;
                    double dayDl = 0;

                    if (rtdbJudge == "1")
                    {
                        power = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_POWERTAG"].ToString() });
                        fzd = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_IRRADIANCETAG"].ToString() });
                        dayDl = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_ELECTAG"].ToString() });
                    }
                    else
                    {
                        power = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_POWERTAG"].ToString() });
                        fzd = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_IRRADIANCETAG"].ToString() });
                        dayDl = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_ELECTAG"].ToString() });
                    }
                    if (!double.IsNaN(power))
                        dr["power"] = Math.Round(Convert.ToDouble(power.ToString()), 2);
                    else
                        dr["power"] = null;
                    dr["lat"] = Convert.ToDouble(dt.Rows[i]["D_LAT"].ToString());
                    dr["long"] = Convert.ToDouble(dt.Rows[i]["D_LONG"].ToString());

                    dr["rl"] = Convert.ToDouble((rl / 1000).ToString("f2"));
                    if (!double.IsNaN(dayDl))
                        dr["dl"] = Math.Round(Convert.ToDouble(dayDl), 2);
                    else
                        dr["dl"] = 0;

                    StationDAL st = new StationDAL();
                    dr["state"] = st.GetPowerPlantState(dt.Rows[i]["T_ORGID"].ToString());
                }
            return tblDatas;
        }

        public DataTable GetStationByUser(string user)
        {
            DataTable dt = new DataTable();
            strSql = "select T_ORGID From T_SYS_MEMBERORG where T_USERID='" + user + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            /*由于数据表字段修改，查询方法进行修改 20160831 胡进财*/
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    stationId += "'" + dt.Rows[i][0] + "',";
                }
            }


            if (stationId.Length > 0)
                stationId = stationId.Substring(0, stationId.Length - 1);

            strSql = @"select ct.T_CITYDESC,ct.T_CITYID,p.T_ORGID,T_PLANTDESC,p.D_LAT,p.D_LONG,t.T_POWERTAG,t.T_ELECTAG,t.T_IRRADIANCETAG,p.T_IMGURL from T_INFO_PLANT p left join T_BASE_POINTS_ORG t on p.T_ORGID = t.T_ORGID join T_BASE_CITY c on p.T_CITYID = c.T_CITYID join T_BASE_CITY ct on ct.T_CITYID = c.T_PARENTID where p.T_ORGID in(" + stationId + ")";

            stationId = "";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            DataTable tblDatas = new DataTable("Station");
            DataColumn dc = null;

            //赋值给dc，是便于对每一个datacolumn的操作
            dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;//

            dc = tblDatas.Columns.Add("stationId", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("stationName", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("city", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("cityID", Type.GetType("System.String"));
            //dc = tblDatas.Columns.Add("data", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("power", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("rl", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("dl", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("lat", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("long", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("ratio", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("state", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("img", Type.GetType("System.String"));
            DataRow dr;
            if (dt != null && dt.Rows.Count > 0)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strSql = "select T_DISTRICTID From T_BASE_DISTRICT where T_ORGID='" + dt.Rows[i]["T_ORGID"] + "'";
                    DataTable dtD = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

                    double rl = 0;
                    for (int k = 0; k < dtD.Rows.Count; k++)
                    {
                        strSql = " select top 1 D_RL From T_INFO_RL where T_ORGID='" + dtD.Rows[k][0] + "' order by T_TIME desc";
                        object obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
                        if (obj != null)
                            rl += Convert.ToDouble(obj);
                    }

                    dr = tblDatas.NewRow();
                    dr["city"] = dt.Rows[i]["T_CITYDESC"].ToString();
                    dr["img"] = dt.Rows[i]["T_IMGURL"].ToString();
                    dr["cityID"] = dt.Rows[i]["T_CITYID"].ToString();
                    dr["stationId"] = dt.Rows[i]["T_ORGID"].ToString();
                    dr["stationName"] = dt.Rows[i]["T_PLANTDESC"].ToString();

                    double power = 0;
                    double fzd = 0;
                    double dayDl = 0;

                    if (rtdbJudge == "1")
                    {
                        power = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_POWERTAG"].ToString() });
                        fzd = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_IRRADIANCETAG"].ToString() });
                        dayDl = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_ELECTAG"].ToString() });
                    }
                    else
                    {
                        power = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_POWERTAG"].ToString() });
                        fzd = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_IRRADIANCETAG"].ToString() });
                        dayDl = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_ELECTAG"].ToString() });
                    }

                    if (!double.IsNaN(power))
                        dr["power"] = Math.Round(Convert.ToDouble(power.ToString()), 2);
                    else
                        dr["power"] = null;
                    dr["lat"] = Convert.ToDouble(dt.Rows[i]["D_LAT"].ToString());
                    dr["long"] = Convert.ToDouble(dt.Rows[i]["D_LONG"].ToString());

                    dr["rl"] = Convert.ToDouble((rl / 1000).ToString("f2"));
                    if (!double.IsNaN(dayDl))
                        dr["dl"] = Math.Round(Convert.ToDouble(dayDl), 2);
                    else
                        dr["dl"] = 0;

                    StationDAL st = new StationDAL();
                    dr["state"] = st.GetPowerPlantState(dt.Rows[i]["T_ORGID"].ToString());

                    tblDatas.Rows.Add(dr);
                }
            return tblDatas;
        }

        public DataTable GetStations(string userId, int count, int pageIndex)
        {
            DataTable dt = new DataTable();
            strSql = "select top " + count + " m.ID_KEY,m.T_ORGID From T_SYS_MEMBERORG m inner join T_INFO_PLANT p on m.T_ORGID = p.T_ORGID where T_USERID='" + userId + "' and m.ID_KEY not in (select Top " + count * (pageIndex - 1) + "  m.ID_KEY From T_SYS_MEMBERORG m inner join T_INFO_PLANT p on m.T_ORGID = p.T_ORGID order  by m.ID_KEY asc)";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            /*由于数据表字段修改，查询方法进行修改 20160831 胡进财*/
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    stationId += "'" + dt.Rows[i][1] + "',";
                }
            }


            if (stationId.Length > 0)
                stationId = stationId.Substring(0, stationId.Length - 1);

            strSql = @"select p.T_ORGID,T_PLANTDESC,p.D_LAT,p.D_LONG,t.T_POWERTAG,t.T_ELECTAG,t.T_IRRADIANCETAG from T_INFO_PLANT p left join T_BASE_POINTS_ORG t on p.T_ORGID = t.T_ORGID where p.T_ORGID in(" + stationId + ")";
            stationId = "";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            //  double val = dl.GetRealTimeValueWithOpen("tag1", 0);

            DataTable tblDatas = new DataTable("Station");
            DataColumn dc = null;

            //赋值给dc，是便于对每一个datacolumn的操作
            dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
            dc.AutoIncrement = true;//自动增加
            dc.AutoIncrementSeed = 1;//起始为1
            dc.AutoIncrementStep = 1;//步长为1
            dc.AllowDBNull = false;//

            dc = tblDatas.Columns.Add("stationId", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("stationName", Type.GetType("System.String"));
            //dc = tblDatas.Columns.Add("data", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("power", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("rl", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("dl", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("lat", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("long", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("ratio", Type.GetType("System.String"));
            dc = tblDatas.Columns.Add("state", Type.GetType("System.String"));
            DataRow dr;
            if (dt != null && dt.Rows.Count > 0)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strSql = "select T_DISTRICTID From T_BASE_DISTRICT where T_ORGID='" + dt.Rows[i]["T_ORGID"] + "'";
                    DataTable dtD = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

                    double rl = 0;
                    for (int k = 0; k < dtD.Rows.Count; k++)
                    {
                        strSql = " select top 1 D_RL From T_INFO_RL where T_ORGID='" + dtD.Rows[k][0] + "' order by T_TIME desc";
                        object obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
                        if (obj != null)
                            rl += Convert.ToDouble(obj);
                    }

                    dr = tblDatas.NewRow();
                    dr["stationId"] = dt.Rows[i]["T_ORGID"].ToString();
                    dr["stationName"] = dt.Rows[i]["T_PLANTDESC"].ToString();

                    double power = 0;
                    double fzd = 0;
                    double dayDl = 0;

                    if (rtdbJudge == "1")
                    {
                        power = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_POWERTAG"].ToString() });
                        fzd = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_IRRADIANCETAG"].ToString() });
                        dayDl = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { dt.Rows[i]["T_ELECTAG"].ToString() });
                    }
                    else
                    {
                        power = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_POWERTAG"].ToString() });
                        fzd = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_IRRADIANCETAG"].ToString() });
                        dayDl = (double)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { dt.Rows[i]["T_ELECTAG"].ToString() });
                    }

                    if (!double.IsNaN(power))
                        dr["power"] = Math.Round(Convert.ToDouble(power.ToString()), 2);
                    else
                        dr["power"] = null;
                    dr["lat"] = Convert.ToDouble(dt.Rows[i]["D_LAT"].ToString());
                    dr["long"] = Convert.ToDouble(dt.Rows[i]["D_LONG"].ToString());

                    dr["rl"] = Convert.ToDouble((rl / 1000).ToString("f2"));
                    if (!double.IsNaN(dayDl))
                        dr["dl"] = Math.Round(Convert.ToDouble(dayDl), 2);
                    else
                        dr["dl"] = 0;

                    StationDAL st = new StationDAL();
                    dr["state"] = st.GetPowerPlantState(dt.Rows[i]["T_ORGID"].ToString());
                }
            return tblDatas;
        }

        public DataTable GetPrivince(string user)
        {
            DataTable dt = new DataTable();
            strSql = "select T_ORGID From T_SYS_MEMBERORG where T_USERID='" + user + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    stationId += "'" + dt.Rows[i][0] + "',";
                }
            }

            if (stationId.Length > 0)
                stationId = stationId.Substring(0, stationId.Length - 1);

            strSql = @"select distinct ct.T_CITYDESC,ct.T_CITYID from T_INFO_PLANT p left join T_BASE_CITY c on p.T_CITYID = c.T_CITYID join T_BASE_CITY ct on ct.T_CITYID = c.T_PARENTID where p.T_ORGID in(" + stationId + ")";

            stationId = "";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dt;
        }
        private static string stationId = "";
        public void GetList(DataTable dtOrg, DataTable dtStation)
        {
            string orgids = "";
            for (int i = 0; i < dtOrg.Rows.Count; i++)
            {
                bool judge = false;
                for (int k = 0; k < dtStation.Rows.Count; k++)
                {
                    if (dtOrg.Rows[i][0].ToString().Trim() == dtStation.Rows[k][0].ToString().Trim())
                    {
                        judge = true;
                        stationId += "'" + dtStation.Rows[k][0].ToString() + "',";
                        break;
                    }
                }
                if (judge == false)
                    orgids += "'" + dtOrg.Rows[i][0] + "',";
            }
            DataTable dt = new DataTable();
            if (orgids != "")
            {
                orgids = orgids.Substring(0, orgids.Length - 1);
                strSql = "select T_ORGID from T_BASE_ORG where T_PARENTID in(" + orgids + ")";
                dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
                GetList(dt, dtStation);
            }
        }

        //取得所有用户的列表以及每个用户的角色ID
        public DataTable GetAllUserWithGrpId()
        {
            strSql = "select T_SYS_MEMBERINFO.ID_KEY,T_SYS_MEMBERINFO.T_USERID,T_SYS_MEMBERINFO.T_USERNAME,T_SYS_MEMBERINFO.T_PASSWORD,T_SYS_MEMBERINFO.T_LANGUAGE,T_SYS_MEMBERINFO.T_PHONE,T_SYS_MEMBERINFO.T_EMAIL,T_SYS_MEMBERGRP.T_GRPID from T_SYS_MEMBERINFO left JOIN T_SYS_MEMBERGRP ON T_SYS_MEMBERGRP.T_USERID=T_SYS_MEMBERINFO.T_USERID";
            dtTable = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            dtTable.Columns.Add("T_ORGID", typeof(string));
            dtTable.Columns.Add("T_ORGDESC_CN", typeof(string));
            dtTable.Columns.Add("T_ORGDESC_EN", typeof(string));
            DataTable dtOrg = new DataTable();
            string sql2 = "";
            for (int i = 0; i < dtTable.Rows.Count; i++)
            {
                string strOrgId = ""; string strOrgCn = ""; string strOrgEn = "";
                sql2 = "select * from T_SYS_MEMBERORG left JOIN T_BASE_ORG ON T_SYS_MEMBERORG.T_ORGID = T_BASE_ORG.T_ORGID where T_SYS_MEMBERORG.T_USERID='" + dtTable.Rows[i]["T_USERID"] + "'";
                dtOrg = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { sql2, strErrMsg });
                for (int j = 0; j < dtOrg.Rows.Count; j++)
                {
                    strOrgId = strOrgId + dtOrg.Rows[j]["T_ORGID"].ToString();
                    strOrgCn = strOrgCn + dtOrg.Rows[j]["T_ORGDESC_CN"].ToString();
                    strOrgEn = strOrgEn + dtOrg.Rows[j]["T_ORGDESC_EN"].ToString();
                    if (j != dtOrg.Rows.Count - 1) { strOrgId = strOrgId + ","; strOrgCn = strOrgCn + ","; strOrgEn = strOrgEn + ","; }
                }
                dtTable.Rows[i]["T_ORGID"] = strOrgId;
                dtTable.Rows[i]["T_ORGDESC_CN"] = strOrgCn;
                dtTable.Rows[i]["T_ORGDESC_EN"] = strOrgEn;
            }
            return dtTable;
        }

        #region 获取电站信息
        public DataTable GetStation(string uid)
        {
            DataTable dt = new DataTable();
            strSql = "select T_ORGID from T_SYS_MEMBERORG where T_USERID='" + uid + "'";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            string id = "";
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    id += "'" + dt.Rows[i][0] + "',";
                }
                id = id.Substring(0, id.Length - 1);
            }
            GetId(id);

            if (ids.Length > 0)
            {
                ids = ids.Substring(0, ids.Length - 1);
            }
            strSql = "select T_ORGID from T_BASE_ORG where T_PARENTID in(" + ids + ") or T_ORGID in(" + ids + ")";
            ids = "";
            dt = new DataTable();
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            if (dt != null & dt.Rows.Count > 0)
            {
                strSql = "select T_ORGID from T_INFO_PLANT";

                DataTable dtStations = new DataTable();

                dtStations = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

                GetList(dt, dtStations);
            }
            if (stationId.Length > 0)
                stationId = stationId.Substring(0, stationId.Length - 1);
            strSql = "select T_ORGID from T_SYS_MEMBERORG where T_ORGID in(" + stationId + ")";
            stationId = "";
            //strSql = "select T_ORGID from T_SYS_MEMBERORG where T_USERID='" + uid + "'";
            dtTable = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dtTable;
        }
        #endregion



        #region Email
        public string GetEmail(string uid)
        {
            strSql = "select T_EMAIL from T_SYS_MEMBERINFO where T_USERID='" + uid + "'";
            objJudge = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            string email = "";
            if (objJudge != null)
                email = objJudge.ToString();
            return email;
        }
        #endregion

        #region Phone
        public string GetPhone(string uid)
        {
            strSql = "select T_PHONE from T_SYS_MEMBERINFO where T_USERID='" + uid + "'";
            objJudge = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            string email = "";
            if (objJudge != null)
                email = objJudge.ToString();
            return email;
        }
        #endregion

        #region Task
        public DataTable GetTask(string uid, string st, string et)
        {
            strSql = "select u.ID_KEY,u.T_USERID,u.T_TASK,u.T_PERFORMANCE,u.T_ASSESS,u.I_FLAG,u.D_POINT,u.T_TIME,T_ORGID,m.T_USERNAME from(select * from T_INFO_INTERVENTION where T_USERID='" + uid + "' and T_TIME between '" + st + "' and '" + et + "') u inner join T_SYS_MEMBERINFO m on u.T_USERID=m.T_USERID ORDER BY u.T_TIME ASC";
            dtTable = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dtTable;
        }
        public DataTable GetTaskPage(string uid, string st, string et, int num, int index)
        {
            strSql = "select u.ID_KEY,u.T_USERID,u.T_TASK,u.T_PERFORMANCE,u.T_ASSESS,u.I_FLAG,u.D_POINT,u.T_TIME,T_ORGID,m.T_USERNAME from(select top " + num + " *from T_INFO_INTERVENTION where T_USERID='" + uid + "' and T_TIME between '" + st + "' and '" + et + "' and ID_KEY not in(select top " + (num * (index - 1)) + " ID_KEY from T_INFO_INTERVENTION where T_USERID='" + uid + "' and T_TIME between '" + st + "' and '" + et + "'  order by T_TIME asc) order by T_TIME asc) u inner join T_SYS_MEMBERINFO m on u.T_USERID=m.T_USERID";
            dtTable = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            return dtTable;
        }
        #endregion

        #region 用户操作 记录
        public bool AddLog(string userId, string connect, DateTime time)
        {
            strSql = "insert into T_SYS_LOG (T_USERID,T_CONNECT,T_TIME) values ('" + userId + "','" + connect + "','" + time + "')";
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 用户Log查询
        public int GetLogTotalCount(string user, string st, string et)
        {
            strSql = @"select count(*) from T_SYS_LOG where T_USERID='" + user + "' and T_TIME between '" + st + "' and '" + et + "'";

            return (int)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunRowCount", new object[] { strSql, strErrMsg });
        }
        public DataTable GetLog(int pageSize, int pageIndex, string user, string st, string et)
        {
            strSql = @"select top " + pageSize + " ID_KEY,T_USERID,T_CONNECT,T_TIME from T_SYS_LOG where ID_KEY not in(select top " + ((pageIndex - 1) * pageSize) + " ID_KEY from T_SYS_LOG  where T_USERID='" + user + "' and T_TIME between '" + st + "' and '" + et + "' order by ID_KEY desc)  and T_USERID='" + user + "' and T_TIME between '" + st + "' and '" + et + "'  order by ID_KEY desc";

            return (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
        }
        #endregion
    }
}
